package org.ehe.finance.payable.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.excel.utils.ExcelUtil;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.finance.payable.domain.ErpFinancePayable;
import org.ehe.finance.payable.domain.bo.PayableBo;
import org.ehe.finance.payable.domain.vo.PayableResponseVO;
import org.ehe.finance.payable.mapper.PayableMapper;
import org.ehe.finance.payable.service.PayableService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 应付账款管理
 * @author :zhangnn
 * @className :PayableController
 * @description: TODO
 * @date 2025-09-02 10:23:16
 */

@RestController
@RequestMapping("/finance/payable")
@RequiredArgsConstructor
public class PayableController extends BaseController {

    private final PayableService payableService;

    /**
     * 分页查询应付账款
     * @param queryVO
     * @return
     */
    @SaCheckPermission("finance:payable:list")
    @GetMapping("/list")
    public TableDataInfo<PayableResponseVO> list(PayableBo queryVO,PageQuery pageQuery) {
        TableDataInfo<PayableResponseVO> page = payableService.selectPayablePage(queryVO,pageQuery);
        return page;
    }

    /**
     * 查询应付账款详情
     * @param id
     * @return
     */
    @SaCheckPermission("finance:payable:query")
    @GetMapping("/{id}")
    public R<ErpFinancePayable> getInfo(@PathVariable Long id) {
        ErpFinancePayable payable = payableService.getPayableDetail(id);
        return R.ok("查询应付账款详情成功",payable);
    }

    /**
     * 创建应付账款
     * @param payableDTO
     * @return
     */
    @SaCheckPermission("finance:payable:add")
    @Log(title = "应付账款", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody PayableBo payableDTO) {
        boolean result = payableService.createPayable(payableDTO);
        return toAjax(result);
    }

    /**
     * 更新应付账款
     * @param payableDTO
     * @return
     */
    @SaCheckPermission("finance:payable:edit")
    @Log(title = "应付账款", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody PayableBo payableDTO) {
        boolean result = payableService.updatePayable(payableDTO);
        return toAjax(result);
    }

    /**
     * 删除应付账款
     * @param ids
     * @return
     */
    @SaCheckPermission("finance:payable:remove")
    @Log(title = "应付账款", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@Parameter(description = "应付账款ID，多个用逗号分隔") @PathVariable String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
            .map(Long::parseLong)
            .toList();

        if (idList.size() == 1) {
            return toAjax(payableService.deletePayable(idList.get(0)));
        } else {
            return toAjax(payableService.batchDeletePayable(idList));
        }
    }

    /**
     * 更新付款金额
     * @param id
     * @param amount
     * @return
     */
    @SaCheckPermission("finance:payable:payment")
    @Log(title = "应付账款付款", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}/payment")
    public R<Boolean> updatePayment(@Parameter(description = "应付账款ID") @PathVariable Long id,
                                    @Parameter(description = "付款金额") @RequestParam BigDecimal amount) {
        boolean result = payableService.updatePaymentAmount(id, amount);
        return R.ok("应付账款付款",result);
    }

    /**
     * 查询即将到期应付账款
     * @param days
     * @return
     */
    @SaCheckPermission("finance:payable:due")
    @GetMapping("/due")
    public R<List<ErpFinancePayable>> getDuePayables(@Parameter(description = "天数，默认7天")
                                                         @RequestParam(defaultValue = "7") int days) {
        List<ErpFinancePayable> duePayables = payableService.getDuePayables(days);
        return R.ok("查询即将到期应付账款",duePayables);
    }

    /**
     * 供应商应付统计
     * @return
     */
    @SaCheckPermission("finance:payable:statistics")
    @GetMapping("/statistics/supplier")
    public R<List<PayableMapper.PayableStatistics>> getSupplierStatistics() {
        List<PayableMapper.PayableStatistics> statistics =
            payableService.getPayableStatisticsBySupplier();
        return R.ok("供应商应付统计",statistics);
    }

    /**
     * 生成单据号
     * @return
     */
    @SaCheckPermission("finance:payable:add")
    @GetMapping("/generate-bill-no")
    public R<String> generateBillNo() {
        String billNo = payableService.generateBillNo();
        return R.ok("生成单据号成功", billNo);
    }

    /**
     * 导出应付账款
     * @param response
     * @param queryVO
     */
//    @SaCheckPermission("finance:payable:export")
//    @Log(title = "应付账款", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, PageQuery queryVO) {
//        // 不分页查询所有数据
//        queryVO.setPageNum(1);
//        queryVO.setPageSize(Integer.MAX_VALUE);
//
//        List<ErpFinancePayable> list = payableService.selectPayablePage(queryVO).getRecords();
//        ExcelUtil<ErpFinancePayable> util = new ExcelUtil<>(ErpFinancePayable.class);
//        util.exportExcel(response, list, "应付账款数据");
//    }
}
